<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑 -->

    <el-card class="box-card">
      <!-- 搜索框 -->
      <div slot="header">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input
              placeholder="输入内容"
              v-model="usersReq.query"
              clearable
              @clear="getMangerList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getMangerList"
              ></el-button>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" @click="addDialogVisible = true"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </div>
      <!-- 搜索框 -->

      <el-table :data="usersList" stripe border>
        <el-table-column type="index"> </el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <el-table-column label="角色" prop="role_name"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="switchState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220px">
          <template slot-scope="scope">
            <!-- {{scope.column}} -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="editUserInfo(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteUser(scope.row.id)"
            ></el-button>

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="small"
                icon="el-icon-setting"
                type="warning"
                @click="allotUserRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <div class="pagination-box bottom">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="usersReq.pagenum"
          :page-sizes="[1, 2, 3, 4]"
          :page-size="usersReq.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNum"
        >
        </el-pagination>
      </div>
      <!-- 分页功能 -->

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        @close="$refs.addRuleForm.resetFields()"
        :visible.sync="addDialogVisible"
        width="30%"
      >
        <el-form
          :model="addRuleForm"
          status-icon
          :rules="addRules"
          ref="addRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="addRuleForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="addRuleForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addRuleForm.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="addRuleForm.mobile"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 对话框区域End -->

      <!-- 修改用户信息对话框 -->
      <el-dialog title="修改信息" :visible.sync="editDialogVisible" width="30%">
        <el-form
          :model="editRuleForm"
          :rules="editRules"
          ref="editRuleForm"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editRuleForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editRuleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editRuleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogCancel()">取 消</el-button>
          <el-button type="primary" @click="editDialogSure()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息对话框End -->

      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="allotRoleDialogVisible"
        width="30%"
      >
        <el-form ref="allotRoleForm" :model="curUserObj">
          <el-form-item>
            <div>当前用户：{{ curUserObj.username }}</div>
            <div>当前角色：{{ curUserObj.role_name }}</div>
            <div>
              分配新角色：
              <el-select v-model="selectedRoleId" placeholder="请选择角色">
                <el-option
                  v-for="item in rolesList"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="allotRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRoleSure">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框End -->
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var validitymobile = function (rule, value, callback) {
      let regExp = /^1[34578]\d{9}$/;

      if (!regExp.test(value)) {
        return callback(new Error("请输入合法的手机号"));
      }
      callback();
    };
    return {
      // 获取用户的参数列表
      usersReq: {
        query: "", // 根据用户名搜索
        pagenum: 1,
        pagesize: 2,
      },
      usersList: [],
      // 角色列表
      rolesList: [],
      totalNum: 0,
      // 添加用户对话框的显示
      addDialogVisible: false,
      // 修改用户信息对话框
      editDialogVisible: false,
      // 分配角色对话框
      allotRoleDialogVisible: false,
      // 当前操纵的用户
      curUserObj: {},
      selectedRoleId: "",

      // 添加用户的表单验证
      addRuleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3到10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, max: 12, message: "请输入5到12个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入合法的邮箱地址", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validitymobile, trigger: "blur" },
        ],
      },
      editRuleForm: {
        username: "",
        email: "",
        mobile: "",
      },
      editRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入合法的邮箱地址", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validitymobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getMangerList();
    this.setRolesList();
  },

  methods: {
    async getMangerList() {
      let { data: res } = await this.$http("/users", {
        params: this.usersReq,
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.usersList = res.data.users;

      this.totalNum = res.data.total;
      this.usersReq.pagenum = res.data.pagenum;
      console.log(this.usersList);
    },

    // 改变当前页
    handleCurrentChange(curPage) {
      this.usersReq.pagenum = curPage;
      this.getMangerList();
    },
    // 每页显示数量
    handleSizeChange(size) {
      this.usersReq.pagesize = size;
      this.getMangerList();
    },

    // 监听Switch开关状态
    async switchState(payload) {
      let { data: res } = await this.$http.put(
        `users/${payload.id}/state/${payload.mg_state}`
      );
      console.log(res.meta.status);
      if (res.meta.status != 200) {
        payload.meta.status = !payload.meta.status;
        return this.$message.error("状态切换失败");
      }
      this.$message.success("状态切换成功");
      this.getMangerList();
    },

    // 添加用户
    addUser() {
      this.$refs.addRuleForm.validate(async (valid) => {
        // 检测表单输入框是否验证正确
        if (!valid) return;

        let { data: res } = await this.$http.post("/users", this.addRuleForm);

        if (res.meta.status != 201) return this.$message.error("添加用户失败");

        this.$message.success("添加用户成功");

        // 隐藏添加用户对话框
        this.addDialogVisible = false;

        // 重新获取用户列表
        this.getMangerList();
      });
    },

    // 修改用户信息
    async editUserInfo(id) {
      let { data: res } = await this.$http.get(`/users/${id}`);
      this.editRuleForm = res.data;
      this.editDialogVisible = true;
      this.curUserObj.id = id;
    },
    // 监听修改用户对话框关闭按钮
    editDialogCancel() {
      this.$refs.editRuleForm.resetFields();
      this.editDialogVisible = false;
    },
    // 监听修改用户对话框确定按钮
    editDialogSure() {
      this.$refs.editRuleForm.validate(async (valid) => {
        if (!valid) return;

        // 发起修改用户信息的数据请求
        let { data: res } = await this.$http.put(
          `/users/${this.editRuleForm.id}`,
          {
            email: this.editRuleForm.email,
            mobile: this.editRuleForm.mobile,
          }
        );
        if (res.meta.status != 200)
          return this.$message.error("用户信息修改失败");

        // 重新获取用户列表
        this.getMangerList();

        // 隐藏修改对话框
        this.editDialogVisible = false;

        // 成功提示信息
        this.$message.success("修改成功");
      });
    },
    // 删除用户
    deleteUser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let { data: res } = await this.$http.delete(`/users/${id}`);
          if (res.meta.status != 200)
            return this.$message.error("删除用户失败");
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          // 重新获取用户列表
          this.getMangerList();
        })
        .catch((res) => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 全部权限列表
    async setRolesList() {
      let { data: res } = await this.$http("/roles");
      this.rolesList = res.data;
    },

    // 分配用户角色
    allotUserRole(payload) {
      this.curUserObj = payload;
      this.allotRoleDialogVisible = true;
    },

    // 确定分配角色
    async allotRoleSure() {
      if (!this.selectedRoleId) return this.$message.error("请选择用户角色！");

      let { data: res } = await this.$http.put(
        `/users/${this.curUserObj.id}/role`,
        {
          rid: this.selectedRoleId,
        }
      );
      if (res.meta.status != 200) return this.$message.error("更新角色失败");
      this.$message.success("更新角色成功");
      this.getMangerList();
      this.allotRoleDialogVisible = false;

      // 重置对话框选项
      this.curUserObj = {};
      this.selectedRoleId = "";
    },

  
  }, // methodsEnd
};
</script>

<style scoped>
.el-pagination {
  margin-top: 15px;
}
</style>